package com.lollipop.programming.search;

import lombok.extern.slf4j.Slf4j;

import java.util.Arrays;

/**
 * @Author Lollipop
 * @Date 2025/4/7 15:10
 * @Description 二分查找
 */
@Slf4j
public class BinarySearch {
    public static void main(String[] args) {
        int[] array = {1, 10, 5, 7, 22, 11, 13, 30, 17, 19};
        Arrays.sort(array);
        log.info("已排序数组:{}", Arrays.toString(array));
        int target = 11;
        int index = binarySearch(array, target);
        log.info("目标值{}的索引为:{}", target, index);
    }

    private static int binarySearch(int[] array, int target) {
        int left = 0;
        int right = array.length - 1;
        while (left <= right) {
            int mid = left + (right - left) / 2;
            if (array[mid] == target) {
                return mid;
            } else if (array[mid] > target) {
                right = mid - 1;
            } else {
                left = mid + 1;
            }
        }
        return -1;
    }
}


